/*
 * ImageDownloader.java
 *
 * Created on 26 wrzesień 2007, 16:51
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package picassawad;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 *
 * @author jaszczur
 */
public class ImageDownloader {
    
    private List<String> urls;
    
    /** Creates a new instance of ImageDownloader */
    public ImageDownloader(List<String> urls) {
        this.urls = urls;
    }
    
    public void downloadTo(File directory) throws IOException {
        if (! directory.isDirectory()) {
            throw new IllegalArgumentException("Parameter 'directory' must represent a directory!");
        }
        int num = 1;
        for (String url : urls) {
//            System.out.println(url);
            URL u = new URL(url);
            String fn = getFileName(u);
            File file = new File(directory, fn);
            
            if (! file.exists()) {
                
                System.out.print("Pobieranie " + num + ". pliku (" + fn + ") ... ");
                
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                int total = 0;
                long start;
                long stop;
                
                try {
                    in = new BufferedInputStream(u.openStream());
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    
                    byte[] buff = new byte[512];
                    int bytesRead;
                    
                    start = System.currentTimeMillis();
                    while ((bytesRead = in.read(buff)) != -1 ) {
                        out.write(buff, 0, bytesRead);
                        total += bytesRead;
                    }
                    stop = System.currentTimeMillis();
                } finally {
                    in.close();
                    out.close();
                }
                
                System.out.printf("OK [%.1f KiB/s]\n", getDownloadSpeed(total, stop-start));
            } else {
                System.out.println("Plik nr " + num + " (" + fn + ") już istnieje. Pomijam.");
            }
            
            num++;
        }
    }
    
    private String getFileName(URL url) {
        String path = url.getPath();
        return path.substring(path.lastIndexOf('/')+1);
    }
    
    private float getDownloadSpeed(int bytes, long timeMilis) {
        return (((float) bytes)/1024f)/(((float) timeMilis)/1000f);
    }
}
